﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using Sunboxsoft.Common;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Create
{
    /// <summary>
    /// 新增预约单
    /// </summary>
    public partial class CreateBookingBillView : UserControl, IView
    {
        #region Property
        //客户信息
        WebRef.VCustomer modelCustomer = null;
        //车辆信息
        WebRef.VAutomobile modelAutoMobile = null;
        Promise _promise = new Promise();
        #endregion

        #region Method
        public CreateBookingBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.DateTimeValidation(txtBookDate, "预约到店时间"));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtRemark, "备注", true));
        }
        public CreateBookingBillView(WebRef.VCustomer modelCustomer, WebRef.VAutomobile modelAutoMobile)
            : this()
        {
            this.modelCustomer = modelCustomer;
            this.modelAutoMobile = modelAutoMobile;
        }

        /// <summary>
        /// 绑定服务项目
        /// </summary>
        private void BindServiceProject()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                PagedResult<WebRef.EServiceCategory> result = new Service.QueryService().QueryServiceCategoryPagedList(
                    ModuleContext.Current.BusinessId,
                    ModuleContext.Current.StationId,
                    Domain.Constant.CommonStatus.ALL,
                    0,
                    Domain.Constant.PageLimitAll);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        this.TreeListServiceProject.DataSource = result.Data.Items;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }

        /// <summary>
        /// 初始客户&车辆信息
        /// </summary>
        private void InitInfo()
        {
            if (modelCustomer != null)
            {
                this.txtCustomerName.Text = modelCustomer.Name;
                this.txtCustomerTel.Text = modelCustomer.Telephone;
            }
            if (modelAutoMobile != null)
            {
                this.txtCarLPN.Text = modelAutoMobile.LPN;
                this.txtCarVIN.Text = modelAutoMobile.VIN;
                this.txtBrand.Text = modelAutoMobile.BrandName;
                this.txtMaker.Text = modelAutoMobile.MakerName;
                this.txtSeries.Text = modelAutoMobile.SeriesName;
                this.txtModel.Text = modelAutoMobile.ModelName;
            }
        }

        /// <summary>
        /// 数据检查
        /// </summary>
        private bool ValidateData()
        {
            string message = null;
            if (GetListService().Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择服务项目！");
                return false;
            }
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取选中的服务项目
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EBookingService> GetListService()
        {
            List<WebRef.EBookingService> listService = new List<WebRef.EBookingService>();
            TreeListNodes list = this.TreeListServiceProject.Nodes;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].CheckState == CheckState.Checked)
                {
                    WebRef.EBookingService modelService = new WebRef.EBookingService();
                    modelService.ServiceCategoryId = new Guid(list[i].GetValue("Id").ToString());
                    listService.Add(modelService);
                }
            }
            return listService;
        }

        /// <summary>
        /// 创建预约单
        /// </summary>
        private void CreateBookBill()
        {
            WebRef.EBookingBill bill = new WebRef.EBookingBill();
            bill.CustomerId = modelCustomer.Id;
            bill.AutomobileId = modelAutoMobile.Id;
            bill.BusinessId = ModuleContext.Current.BusinessId.Value;
            bill.StationId = ModuleContext.Current.StationId.Value;
            bill.TargetDate = Convert.ToDateTime(txtBookDate.Text.Trim());
            //授理人
            WebRef.VStaffPosition item = SearchLookUpEditUtil.GetSelectedValue<WebRef.VStaffPosition>(this.ctlSearchLookUpSalesManager);
            if (item != null)
            {
                bill.SalesManagerId = item.StaffId;
            }
            bill.IsDeleted = false;
            bill.Memo = txtRemark.Text.Trim();
            WebRef.EBookingService[] servies = GetListService().ToArray<WebRef.EBookingService>();

            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CreateService().CreateBookingBill(bill, servies);
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 保存
        /// </summary>
        private void OnSave_Click(object sender, object e)
        {
            if (ValidateData())
            {
                CreateBookBill();
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        private void OnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }

        /// <summary>
        /// 改变节点选中状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeListServiceProject_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            try
            {
                e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        #endregion

        #region IView 成员

        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存", OnSave_Click))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", OnCancel_Click));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    InitInfo();
                    _promise.Resolve();
                }));
            })
                .Then(() =>
            {
                SearchLookUpEditUtil.BindVStaffPosition(this.ctlSearchLookUpSalesManager, _promise, Domain.Constant.StaffPosts.SalesManager);
            })
                .Then(BindServiceProject)
                .Run(null);
        }
        public void Resume(ViewResumeArgs args)
        {
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("新增预约单");
        }
        #endregion
    }
}
